<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 发布订阅者模式，关键点1、消息队列、发布、订阅、移除
      class Observer {
        // 消息队列
        constructor() {
          this.message = {}
        }
        // 订阅
        $on(type, fn) {
          if (!this.message[type]) {
            this.message[type] = []
          }
          this.message[type].push(fn)
        }
        //发布
        $emit(type,data) {
          if (!this.message[type]) return
          this.message[type].forEach((element) => {
            element(data)
          })
        }
        // 移除 如果只有type移除type的所有事件，如果type和fn都存在移除type里面fn
        $off(type, fn) {
          if (!this.message[type]) return
          if (!fn) {
            this.message[type] = undefined
          } else {
            this.message[type] = this.message[type].filter(
              (item) => item !== fn
            )
          }
        }
      }

      let person1 = new Observer()
      person1.$on('eventA', callbackA)
      person1.$on('eventA', callbackB)
      person1.$on('eventA', callbackC)


      function callbackA(data) {
        console.log('callbackA 回调',data)
      }
      function callbackB(data) {
        console.log('callbackB 回调',data)
      }
      function callbackC(data) {
        console.log('callbackC 回调',data)
      }
      person1.$emit('eventA',{age:12})
    </script>
  </body>
</html>
